package com.passivator.web;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class ContextListener implements ServletContextListener,
		HttpSessionListener {

	@Resource(name = "jms/ConnectionFactory")
	private QueueConnectionFactory connectionFactory;

	@Resource(name = "jms/PassivatorQueue")
	private Queue destination;

	private final static Logger logger = Logger.getLogger(ContextListener.class
			.getName());
	
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub

	}

	public void contextInitialized(ServletContextEvent arg0) {
		logger.info("Aplicacion iniciada");

	}

	public void sessionCreated(HttpSessionEvent arg0) {
		logger.info("Session iniciada");

	}

	public void sessionDestroyed(HttpSessionEvent arg0) {

		HttpSession ses = arg0.getSession();
		passivateSession(ses);
	}

	private void passivateSession(HttpSession ses) {

		// Creamos la conexion a la cola JMS
		try {
			// Serializamos la sesion
			byte[] content = serializeSession(ses);

			QueueConnection connection = connectionFactory.createQueueConnection();
			QueueSession session = connection.createQueueSession(true,
					Session.AUTO_ACKNOWLEDGE);
			
			QueueSender sender = session.createSender(destination);

			// Creamos el mensaje y lo enviamos
			ObjectMessage message = session.createObjectMessage();
			message.setObject(content);
			sender.send(message);
		} catch (IOException ex) {
			logger.log(Level.SEVERE, "No se puede serializar la sesion", ex);
		} catch (JMSException ex) {
			logger.log(Level.SEVERE,
					"No se ha podido pasivizar la sesion caducada", ex);
		}

	}

	private byte[] serializeSession(HttpSession ses) throws IOException {

		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutput out = new ObjectOutputStream(bos);
		out.writeObject(ses);
		out.close();

		byte[] array = bos.toByteArray();

		return array;
	}
}
